﻿#pragma once

#include "common.h"
//#include "context.h"
#include "ui/ui.h"
#include "ui/control_base.h"

namespace anip
{
	namespace ui
	{
		class TextField : public WithText<Scrollable<Control>>
		{
		private:
			TextRenderer::StringLayout* _layout = nullptr;
			const TextRenderer::Character* _chs = nullptr;
			int _cindex = 0, _ccol = 0, _cline = 0; // , _cheight = 30;
			vec2 _cpos = { 0, 0 };

		protected:
			void processKey(Key k, ButtonAction action) override;
			void processUnicodeInput(wchar_t ch) override;
			void processMouseEnter() override;
			void processMouseLeave() override;
			void processMouseMove(invec2 pos) override;
			void processMouseButton(MouseButton btn, ButtonAction action) override;
			void processFocus() override;
			void processDefocus() override;

			void discardTextTexture() override;
			void renderText(Texture2D*& tex, outvec2 size) override;

			void inputCharacter(wchar_t ch, bool repeat = false);
			void deleteSelection();

		public:
			TextField(Container* parent = nullptr, invec2 pos = { 0, 0 },
				invec2 size = { 100, 30 }, const wstring& text = L"");

			bool multiline = false;

			bfloat 
				roundRadius = r::RoundRadius,
				hoverFactor = r::Button_HoverFactor;

			bcolor 
				backColor = r::Textfield_BackColor,
				borderColor = r::Textfield_BorderColor,
				focusedBorderColor = r::Textfield_FocusedBorderColor,
				cursorColor = r::CursorColor;

			// Note: to reject the input character, set `ch` to zero.
			std::function<void(TextField& self, wchar_t& ch, bool repeat)> onInput;

			// should setText() etc. trigger this? maybe not, as per Slider etc
			std::function<void(TextField& self)> onTextChanged;

			void setText(const wstring& t) override;

			int getCursorIndex() const { return _cindex; }
			void setCursorIndex(int i);

			void paint() override;
			void flow(Flow& f) override;
		};
	}
}